package com.validator.plus.config;


import com.validator.plus.aop.GlobalExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器
 */
@Configuration
public class WebMvcAutoConfig implements WebMvcConfigurer {

    /**
     * 全局异常处理
     */
    @Bean
    GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    /**
     * 配置请求初始化Filter
     *
     * @param servletPath 前端控制器路径，只拦截到Controller的请求
     */
    @Bean
    FilterRegistrationBean requestContextFilter(
            @Value("${spring.mvc.servlet.path}") String servletPath) {
        FilterRegistrationBean<RequestContextFilter> bean = new FilterRegistrationBean<>(new RequestContextFilter());
        String pattern = servletPath.replaceAll("/+$", "") + "/*";
        bean.addUrlPatterns(pattern);
        bean.setOrder(2);
        return bean;
    }
}
